package data.salesmanager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

import po.ResultMessage;
import po.SalesManagerPO;
import service.SalesmanagerDataService;

public class SalesmanagerData extends UnicastRemoteObject implements SalesmanagerDataService{
	
	private static final long serialVersionUID = 1L;
	
	private ArrayList<SalesManagerPO> salesmanagerList = new ArrayList<SalesManagerPO>();
	
	private ObjectInputStream inputStream;
    private ObjectOutputStream outputStream;
	
	public SalesmanagerData() throws RemoteException {
		try {
			initData();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void initData() throws IOException{
		if(new File("salesmanager").exists()){	
			FileInputStream fis=new FileInputStream("salesmanager");
			inputStream=new ObjectInputStream(fis);
			
			while(fis.available()>0){
				try {
					salesmanagerList.add((SalesManagerPO)inputStream.readObject());
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
			inputStream.close();
		}
		else{
			SalesManagerPO salesmanager1 = new SalesManagerPO("111", "111");
			salesmanagerList.add(salesmanager1);
		}
	}
	
	public ResultMessage login(SalesManagerPO salesManager)
			throws RemoteException {
		for(SalesManagerPO s: salesmanagerList){
			if(s.isSameAccount(salesManager)){
				if(s.isSamePassword(salesManager)){
					return ResultMessage.SUCCEED;
				}
				else{
					//return ResultMessage.PASSWORDERROR;
				}
			}
		}
		return ResultMessage.ERROR;
	}
	
	public void save() throws IOException{
		FileOutputStream fos=new FileOutputStream("data/salesmanager");
		outputStream=new ObjectOutputStream(fos);	
	
		for (SalesManagerPO i:salesmanagerList) {
			outputStream.writeObject(i);
		}
		outputStream.close();
	}
}